#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>

/**
 * Echo-server gets a message from client and 
 * sends it back.
 */

int main() {
  int listener;
  struct sockaddr_in addr;
  struct sockaddr_in client;
  socklen_t size_of_client;
  char buf[1024];
  int bytes_read;
  listener = socket(AF_INET, SOCK_DGRAM, 0);
  if (listener < 0) {
    perror("socket");
    return errno;
  }
  addr.sin_family = AF_INET;
  addr.sin_port = htons(32000);
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  if (bind(listener, (struct sockaddr *)&addr,
           sizeof(addr)) < 0) {
    perror("bind");
    return errno;
  }
  while (1) {
    bytes_read = recvfrom(listener, buf, 1024, 0, 
                          (struct sockaddr *)&client, 
                          &size_of_client);
    if (bytes_read > 0) {
      sendto(listener, buf, bytes_read, 0, 
             (struct sockaddr *)&client, size_of_client);
      buf[bytes_read] = 0;
      printf("Got from client: %s\n", buf);
    }
  }
  close(listener);
  return 0;
}
